package bibliotecas;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;

public class JCalendar extends JPanel{

	private static final long serialVersionUID = 5703297056080400755L;
	
	private SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
	private DecimalFormat formatoDoisZeros = new DecimalFormat("00");
	
	private JPanel painel = new JPanel();
	private JSmartTable tabela = new JSmartTable(new String[] {"DOM","SEG","TER","QUA","QUI","SEX","SAB"});
	private JSmartButton botaoProximo = new JSmartButton(">>");
	private JSmartButton botaoAnterior = new JSmartButton("<<");
	public JTextField textoDescricao = new JTextField("01/01/2014");
	private String dataHoje = formatoData.format(new Date()); 
	private String dataAtual = dataHoje; 
	private static String dataSelecao = null;
	private Component alvo = null;
	
	private int getDia(Date data){
		return Integer.parseInt(formatoData.format(data).split("/")[0]);
	}
	
	private int getMes(Date data){
		return Integer.parseInt(formatoData.format(data).split("/")[1]);
	}
	
	private int getAno(Date data){
		return Integer.parseInt(formatoData.format(data).split("/")[2]);
	}
	
	public void setRetorno(Component cp){
		alvo = cp;
	}
	
	public JCalendar(){
		init();
	}
	
	public JCalendar(Component cp){
		alvo = cp;
		init();
	}
	
	public void redim(){
		tabela.setDimensoes(0,0,getWidth(),getHeight() - 34);
		tabela.tabela.setRowHeight((int) (getHeight() == 0?1:((getHeight() - 70) / 6)));
		painel.setBounds(0,getHeight() - 34,getWidth(),34);
		botaoAnterior.setBounds(2,4,50,25);
		textoDescricao.setBounds(54,4,getWidth() - 108,25);
		botaoProximo.setBounds(getWidth() - 52,4,50,25);
	}
	
	public void init(){
		this.setLayout(null);
		this.addComponentListener(new ComponentAdapter() { @Override 
			public void componentShown(ComponentEvent event){ redim(); }
			public void componentResized(ComponentEvent event){ redim(); }});
		
		tabela.setVisible(true);
		
		tabela.scrollTabela.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
		tabela.tabela.addMouseListener(new MouseAdapter() {	
			@Override
			public void mousePressed(MouseEvent arg0) {
				if(tabela.tabela.getValueAt(tabela.tabela.getSelectedRow(),tabela.tabela.getSelectedColumn()) != null){
					dataAtual = formatoDoisZeros.format(Integer.parseInt(tabela.tabela.getValueAt(tabela.tabela.getSelectedRow(),tabela.tabela.getSelectedColumn()).toString())) + "/" + dataAtual.split("/")[1] + "/" + dataAtual.split("/")[2];
				}
				if(arg0.getClickCount() == 2){
					textoDescricao.setText(dataAtual);
					try{
						JTextField txt = (JTextField) alvo;
						txt.setText(dataAtual);
					}catch(Exception e){
						JLabel txt = (JLabel) alvo;
						txt.setText(dataAtual);
					}
					funcaoAposClique();
				}
			}
		});
		montaCalendario(formatoData.format(new Date()));
		this.add(tabela);
		
		painel.setBackground(new Color(150,150,150));
		painel.setLayout(null);
		this.add(painel);

		botaoAnterior.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				int mesAtual = Integer.parseInt(dataAtual.split("/")[1]);
				mesAtual--;
				if(mesAtual < 1){
					dataAtual = montaData(1,12,Integer.parseInt(dataAtual.split("/")[2]) - 1);
				}else{
					dataAtual = montaData(1,mesAtual,Integer.parseInt(dataAtual.split("/")[2]));
				}
				montaCalendario(montaData(Integer.parseInt(dataAtual.split("/")[0]),
						                  Integer.parseInt(dataAtual.split("/")[1]),
						                  Integer.parseInt(dataAtual.split("/")[2])));
				textoDescricao.setText(dataAtual);
			}
		});
		painel.add(botaoAnterior);
		
		textoDescricao.setText(formatoData.format(new Date()));
		textoDescricao.setEditable(false);
		textoDescricao.setFocusable(false);
		textoDescricao.setHorizontalAlignment(JTextField.CENTER);
		textoDescricao.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.GRAY));
		painel.add(textoDescricao);
		
		botaoProximo.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				int mesAtual = Integer.parseInt(dataAtual.split("/")[1]);
				mesAtual++;
				if(mesAtual > 12){
					dataAtual = montaData(1,1,Integer.parseInt(dataAtual.split("/")[2]) + 1);
				}else{
					dataAtual = montaData(1,mesAtual,Integer.parseInt(dataAtual.split("/")[2]));
				}
				montaCalendario(montaData(Integer.parseInt(dataAtual.split("/")[0]),
						                  Integer.parseInt(dataAtual.split("/")[1]),
						                  Integer.parseInt(dataAtual.split("/")[2])));
				textoDescricao.setText(dataAtual);
			}
		});
		painel.add(botaoProximo);
		
	}

	public void funcaoAposClique() {
		
	}

	private void montaCalendario(String data) {
		int dia = Integer.parseInt(data.split("/")[0]);
		int mes = Integer.parseInt(data.split("/")[1]);
		int ano = Integer.parseInt(data.split("/")[2]);
		
		Calendar c = new GregorianCalendar(ano,mes - 1,dia);
		int ultimoDiames = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		
		ArrayList<String[]> dados = new ArrayList<String[]>();
		for(int i = 1,x;i <= ultimoDiames;i++){
			x = getDiaSemana(montaData(i,mes,ano));
			if(i == 1 || x == 0){
				dados.add(new String[7]);				
			}
			dados.get(dados.size() - 1)[x] = Integer.toString(i);
		}
		
		tabela.modeloTabela.setRowCount(0);
		
		for(int i = 0;i < 6;i++){
			if(i <= dados.size() - 1){
				tabela.modeloTabela.addRow(dados.get(i));
			}
			else{
				tabela.modeloTabela.addRow(new String[7]);
			}
		}
		
		DefaultTableCellRenderer centro = new DefaultTableCellRenderer();
		centro.setHorizontalAlignment(SwingConstants.CENTER);
		tabela.tabela.getColumnModel().getColumn(0).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(1).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(2).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(3).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(4).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(5).setCellRenderer(centro);
		tabela.tabela.getColumnModel().getColumn(6).setCellRenderer(centro);
	}
	
	
	
	private String montaData(int dia,int mes,int ano){
		return formatoDoisZeros.format(dia) + "/" + formatoDoisZeros.format(mes) + "/" + Integer.toString(ano);
	}
	
	private int getDiaSemana(String data) {
		int dia = Integer.parseInt(data.split("/")[0]);
		int mes = Integer.parseInt(data.split("/")[1]);
		int ano = Integer.parseInt(data.split("/")[2]);
		int a = (14 - mes) / 12;
		int y = ano - a;
		int m = mes + (12 * a) - 2;
		int q = dia + ((31 * m) / 12) + y + (y / 4) - (y / 100) + (y / 400);
		return mod(q,7);
	}
	
	private int mod(int valor,int divisor){
		while(valor >= divisor){
			valor = valor - divisor;
		}
		return valor;
	}

}